package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 验证码发送
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;

    //获取体检预约的验证码
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        //调方法随机生成4位数验证码
        Integer validate = ValidateCodeUtils.generateValidateCode(4);

        //调阿里云方法给用户发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validate.toString());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        //将获取的验证码存入jedis中
        Jedis resource = jedisPool.getResource();
        resource.setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,300,validate.toString());
        //释放连接池,即返还对象,如果用户量大于最大分配的对象数,将陷于死等待
        resource.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    //用户登录验证码
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        //调方法随机生成6位数验证码
        Integer validate = ValidateCodeUtils.generateValidateCode(6);

        //调阿里云方法给用户发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validate.toString());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        //将获取的验证码存入jedis中
        Jedis resource = jedisPool.getResource();
        resource.setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,300,validate.toString());
        //释放连接池,即返还对象,如果用户量大于最大分配的对象数,将陷于死等待
        resource.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
